package com.tsvetanv.data.binding.allowed.fields;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;

import com.tsvetanv.data.binding.model.allowed.fields.Person;

import junit.framework.TestCase;

public class AllowedFieldsCommandBeanTest extends TestCase {

	private Person bean;
	private ServletRequestDataBinder binder;
	private MockHttpServletRequest request;

	@Override
	protected void setUp() throws Exception {
		bean = new Person();
		binder = new ServletRequestDataBinder(bean, "beanName");
		request = new MockHttpServletRequest();
	}

	public void testAllowedFieldsCommandBean() {
		binder.setAllowedFields(new String[] { "firstName", "idCard" });

		request.addParameter("firstName", "Tsvetan");
		request.addParameter("lastName", "Vasilev");
		request.addParameter("gender", "M");
		request.addParameter("idCard", "1234");

		binder.bind(request);

		assertEquals("Tsvetan", bean.getFirstName());
		assertNull(bean.getLastName());
		assertEquals('\u0000', bean.getGender());
		assertEquals(1234, bean.getIdCard());
	}

	public void test2AllowedFieldsCommandBean() {
		request.addParameter("firstName", "Tsvetan");
		request.addParameter("lastName", "Vasilev");
		request.addParameter("gender", "M");
		request.addParameter("idCard", "1234");

		binder.bind(request);

		// incorrect calling of setAllowedFieds method
		// (becauset it is after binding) => it will not affect allowed fields
		binder.setAllowedFields(new String[] { "lastName", "gender" });

		assertEquals("Tsvetan", bean.getFirstName());
		assertEquals("Vasilev", bean.getLastName());
		assertEquals('M', bean.getGender());
		assertEquals(1234, bean.getIdCard());

	}

	public void test3AllowedFieldsCommandBean() {
		request.addParameter("firstName", "Tsvetan");
		request.addParameter("lastName", "Vasilev");
		request.addParameter("gender", "M");
		request.addParameter("idCard", "1234");

		binder.setAllowedFields(new String[] { "lastName", "gender" });
		binder.bind(request);

		assertNull(bean.getFirstName());
		assertEquals("Vasilev", bean.getLastName());
		assertEquals('M', bean.getGender());
		assertEquals(0, bean.getIdCard());
	}
}
